package cn.gok.config;

import cn.gok.dao.UserDao;
import cn.gok.entity.User;
import cn.gok.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author shikundai
 * @date 2021/3/21
 * @time 14:00
 * @description
 */
public class SSMRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     * @author shikundai
     * @date 2021/3/21
     * @time 14:01
     * @description 用户授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * @author shikundai
     * @date 2021/3/21
     * @time 14:01
     * @description 用户认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upt = (UsernamePasswordToken) authenticationToken;
        //获取用户名
        String name = upt.getUsername();
        //查询数据库获取用户信息
        User user=userService.getUser(name);
        if (user==null){
            throw new UnknownAccountException("用户名不存在！");
        }
        //用户名，认证凭证，realmName
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(name, user.getPsw(), getName());
        return info;
    }
}
